package com.admin.service.impl;

import com.admin.controller.responseBody.ResponseBody;
import com.admin.entity.Permission;
import com.admin.entity.Role;
import com.admin.mapper.PermissionMapper;
import com.admin.mapper.RoleMapper;
import com.admin.service.IPermissionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author marisheng
 * @since 2019-11-21
 */
@SuppressWarnings("ALL")
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RoleMapper roleMapper;
    /**
     * 跟据角色id查所有权限
     *
     * @param roleId
     * @return
     */
    @Override
    public Map findPermissionByRole(int roleId) {
        List<Map> list = permissionMapper.findPermissionByRole();
        ResponseBody  rootResponsBody = setFirstData(list);
        List responseBodys = add(list,rootResponsBody);

        Map map = new HashMap();
        map.put("data", responseBodys);
       List listArray = permissionMapper.findPermissionIdByRole(roleId);
        map.put("array", listArray);
        return map;
    }

    /**
     * 求根节点下所有子节点
     *
     * @param roleId
     * @param list
     * @param responseBodys
     * @return
     */
    @Override
    public List<ResponseBody> setData(List<Map> list, ResponseBody b) {
        List<ResponseBody> responseBodys = new ArrayList<>();
        for (Map m : list) {
            if (b.getId() == Integer.parseInt(m.get("permission_parent_id").toString())) {
                ResponseBody responseBody = new ResponseBody();
                responseBody.setId(Integer.parseInt(m.get("permission_id").toString()));
                if(m.get("permission_menu_name")!=null) {
                    responseBody.setTitle(m.get("permission_menu_name").toString());
                }else{
                    responseBody.setTitle("未命名");
                }
                responseBody.setEnd(Boolean.getBoolean(m.get("permission_end").toString()));
                responseBodys.add(responseBody);
            }

        }
        return responseBodys;
    }

    /**
     * 求根节点
     *
     * @param roleId
     * @param list
     * @param responseBodys
     * @return
     */
    @Override
    public ResponseBody setFirstData(List<Map> list) {

        for (Map m : list) {
            ResponseBody responseBody = new ResponseBody();

            if (0 == Integer.parseInt(m.get("permission_parent_id").toString())) {
                responseBody.setId(Integer.parseInt(m.get("permission_id").toString()));
                responseBody.setTitle(m.get("permission_menu_name").toString());
                return responseBody;
            }

        }
        throw new RuntimeException("not found root node!");
    }

    /**
     * 判断是否有子节点，有子节点则循环子节点
     *
     * @param roleId
     * @param list
     * @param responseBodys
     * @return
     */
    @Override
    public List<ResponseBody> add(List<Map> list,ResponseBody root) {
        List<ResponseBody> responseBodyAll = new ArrayList<>();


                //查当前节点的子节点
                List<ResponseBody> responseBodys2 = setData(list, root);

                //如果子节点有数据，则再次循环子节点
                if (responseBodys2.size() != 0) {
                    responseBodyAll.add(root);
                    root.setChildren(responseBodys2);
                    for (int j = 0; j < responseBodys2.size(); j++)
                    {
                        add(list,responseBodys2.get(j));
                    }
                }


        return responseBodyAll;
    }

    /**
     * 根据用户保存或删除权限
     *
     * @param permissionArray
     * @param roleId
     * @return
     */
    @Override
    public int saveOrDelPermissionByRole(int[] permissionArray, int roleId) {
        permissionMapper.delPermissionByRole(roleId);
        if (permissionArray != null) {
            int n = permissionMapper.savePermissionWithRole(permissionArray, roleId);
            return n;
        }
        return 0;
    }

    /**
     * 查所有权限
     * @return
     */
    @Override
    public Map findPermission(){
        List<Map> list = permissionMapper.findPermissionByRole();
        ResponseBody  rootResponsBody = setFirstData(list);
        List responseBodys = add(list,rootResponsBody);

        Map map = new HashMap();
        map.put("data", responseBodys);
        return map;
    }

    /**
     * 新增角色和角色的权限
     * @param permissionIdArray
     * @param rolename
     * @return
     */
    @Override
    public int savePermission(int[] permissionIdArray, String rolename){
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_name",rolename);
        List<Role> roles = roleMapper.selectList(queryWrapper);
        Role role = null;
        if (roles.size()==0) {
            role = new Role();
        }else{
            return 0;
        }
        role.setRoleName(rolename);
        int n = roleMapper.insert(role);
        int id = -1;
        if(n>0) {
            id = role.getRoleId();
            if (permissionIdArray != null) {
                int n1 = permissionMapper.savePermissionWithRole(permissionIdArray, id);
                return n1;
            }else{
                return 1;
            }
        }
        return 0;
    }
    @Override
    public int permissionInsert(String url, String text, String end, int pid){
        Permission permission = new Permission();
        permission.setPermissionParentId(pid);
        permission.setPermissionMenuName(text);
        permission.setPermissionUrl(url);
        permission.setPermissionEnd(end);
        permission.setPermissionParentId(pid);
        int n = permissionMapper.insert(permission);
        return n;
    }
    @Override
    public int permissionUpdate(int id,String text,String url,String end){
        Permission permission = permissionMapper.selectById(id);
        permission.setPermissionMenuName(text);
        permission.setPermissionUrl(url);
        permission.setPermissionEnd(end);
        int n = permissionMapper.updateById(permission);
        return n;
    }
    @Override
    public Map findUrlById(int id){
        Map map = permissionMapper.findUrlById(id);
        return map;
    }
    @Override
    public int delById(int id)
    {
        return permissionMapper.deleteById(id);
    }
}
